"""会议室"""
import uuid
import httpx
from loguru import logger

IP_ADDRESS = '192.168.100.120'
PORT = 9009


def signout_handle_room(room_id, employee_id, employee_name):
    """删除会议室人员信息"""  
    for i in room_id:
        device_id, msg = room_search(i)
        logger.bind(log_type='signin').info({"id_card": employee_id, "action": "搜索设备ID", "data": {"device_id": device_id}})

        if msg:
            return None, msg

        # 删除人员信息
        _, msg = delete_user_info(device_id, employee_id)
        if msg:
            return None, msg

        # 删除人脸信息
        _, msg = delete_face_data_record(device_id, employee_id, employee_name)
        if msg:
            return None, msg


def handle_room(room_id, employee_id, employee_name, qrcode_base64):
    """会议室下发权限"""    
    for i in room_id:

        device_id, msg = room_search(i)
        logger.bind(log_type='signin').info({"id_card": employee_id, "action": "搜索设备ID", "data": {"device_id": device_id}})
        if msg:
            return None, msg

        # # 删除人员信息
        # _, msg = delete_user_info(device_id, employee_id)
        # if msg:
        #     return None, msg

        # # 删除人脸信息
        # _, msg = delete_face_data_record(device_id, employee_id, employee_name)
        # if msg:
        #     return None, msg

        # 2. 新增人员信息
        _, msg = add_user_info(device_id, employee_id, employee_name)
        if msg:
            return None, msg
        # 3. 上传人员照片
        face_url, msg = upload_face_picture_by_pic_base64(qrcode_base64, f"{uuid.uuid4().hex}.jpg")
        logger.bind(log_type='signin').info({"id_card": employee_id, "action": "上传人员照片", "data": {"face_url": face_url}})
        if msg:
            return None, msg
        # 4. 新增人脸信息
        _, msg = add_face_data_record(face_url, device_id, employee_id, employee_name)
        if msg:
            return None, msg
        return None, None

def room_search(room_id):
    """查询设备号"""
    url = f"http://{IP_ADDRESS}:{PORT}/smartRoom/v1/room/search"
    params = {"roomId": [room_id]}
    response = httpx.post(url=url, json=params, verify=False).json()
    if response["code"] != 0:
        return None, response["msg"]
    return response["data"]['rooms'][0]["deviceId"], None


def delete_face_data_record(device_code, employee_id, employee_name):
    """删除人脸信息"""
    url = f"http://{IP_ADDRESS}:{PORT}/isupserver/api/mas/v1/meet/deleteFaceDataRecord"
    params = {
        "deviceIndexCode": device_code,
        "bornTime": "1990-01-01",
        "transfer": True,
        "fpid": employee_id,
        "faceLibType": "blackFD",
        "fdid": "1",
        "name": employee_name,
        "operateType": "byTerminal",
        "faceType": "normalFace",
    }
    response = httpx.post(url=url, json=params, verify=False).json()
    logger.bind(log_type='signin').info({"id_card": employee_id, "action": "删除人脸信息", "data": response})
    if response["statusCode"] != 1:
        return None, response["errorMsg"]
    return response, None


def delete_user_info(device_code, employee_id):
    """删除人员信息"""
    url = f"http://{IP_ADDRESS}:{PORT}/isupserver/api/mas/v1/meet/deleteUserInfo"

    params = {
        "deviceIndexCode": device_code,
        "userInfoDelCond": {
            "employeeNoList": [
                {
                    "employeeNo": employee_id,
                }
            ],
            "operateType": "byTerminal",
        }
    }

    response = httpx.post(url=url, json=params, verify=False).json()
    logger.bind(log_type='signin').info({"id_card": employee_id, "action": "删除人员信息", "data": response})

    if response["statusCode"] != 1:
        return None, response["errorMsg"]
    return None, None


def add_user_info(device_code, employee_id, employee_name):
    """新增人员信息"""
    url = f"http://{IP_ADDRESS}:{PORT}/isupserver/api/mas/v1/meet/addUserInfo"
    params = {
        "deviceIndexCode": device_code,
        "userInfo": {
            "employeeNo": employee_id,
            "name": employee_name,
            "roomNumber": 0,
            "userVerifyMode": "face",
            "gender": "unknown",
            "operateType": "byTerminal",
            "numOfCard": 0,
            "closeDelayEnabled": True,
            "checkUser": False,
            "maxOpenDoorTime": 0,
            "openDoorTime": 0,
            "floorNumber": 0,
            "localUIRight": False,
            "userType": "normal",
            "numOfFP": 0,
            "doubleLockRight": False,
            "doorRight": "1",
            "RightPlan": [
                {
                    "doorNo": "1",
                    "planTemplateNo": "1"
                },
            ]
        }
    }
    response = httpx.post(url=url, json=params, verify=False).json()

    logger.bind(log_type='signin').info({"id_card": employee_id, "action": "新增人员信息", "data": response})

    if response["statusCode"] == 1:
        return None, None
    return None, response["errorMsg"]


def upload_face_picture_by_pic_base64(picBase64, filename):
    """上传人员照片"""
    url = f"http://{IP_ADDRESS}:{PORT}/isupserver/api/mas/v1/meet/uploadFacePictureByPicBase64"
    params = {
        "picBase64": picBase64,
        "fileName": filename,
    }
    response = httpx.post(url=url, json=params, verify=False).json()
    if response["code"] != 0:
        return None, response["msg"]
    return response["data"], None


def add_face_data_record(face_url, device_code, employee_id, employee_name):
    """新增人脸信息"""
    url = f"http://{IP_ADDRESS}:{PORT}/isupserver/api/mas/v1/meet/addFaceDataRecord"
    params = {
        "faceURL": face_url,
        "deviceIndexCode": device_code,
        "bornTime": "1990-01-01",
        "transfer": True,
        "fpid": employee_id,
        "faceLibType": "blackFD",
        "fdid": "1",
        "name": employee_name,
        "operateType": "byTerminal",
        "faceType": "normalFace",
    }
    print(params)
    response = httpx.post(url=url, json=params, verify=False).json()
    logger.bind(log_type='signin').info({"id_card": employee_id, "action": "新增人脸信息", "data": response})
    
    if response["statusCode"] != 1:
        return None, response["errorMsg"]
    return None, None
